package com.yllt4cloud.gateway.filter;


import com.yllt4cloud.common.core.constant.SecurityConstants;
import com.yllt4cloud.common.ddbase.constant.entity.SessionEntity;
import com.yllt4cloud.common.ddbase.util.CommonRedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.server.HandlerStrategies;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * @author yaoxj
 * @date 2019/6/5
 * <p>
 * 全局拦截器，作用所有的微服务
 * <p>
 * 1. 对请求头中参数进行处理 from 参数进行清洗
 * 2. 重写StripPrefix = 1,支持全局
 * <p>
 */
@Component
@Slf4j
public class YlltRequestGlobalFilter implements GlobalFilter, Ordered {

	private static final String ALL = "*";
	private static final String MAX_AGE = "18000L";


	@Autowired
	private CommonRedisUtil commonRedisUtil;


	/**
	 * Process the Web request and (optionally) delegate to the next
	 * {@code WebFilter} through the given {@link GatewayFilterChain}.
	 *
	 * @param exchange the current server exchange
	 * @param chain    provides a way to delegate to the next filter
	 * @return {@code Mono<Void>} to indicate when request processing is complete
	 */
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		//先判断session是否存在，不存在，返回登录页面。存在的情况下判断session是否过期，没过期执行以下操作。

		GatewayContext gatewayContext = exchange.getAttribute(GatewayContext.CACHE_GATEWAY_CONTEXT);
		if(gatewayContext!=null&&gatewayContext.getFormData()!=null){
			String sessionId=gatewayContext.getFormData().getFirst("session");

			if(sessionId!=null&&isExpire(sessionId)){//不为空，没过期，重新设置过期时间
				commonRedisUtil.reSetExpire(sessionId);
			}

			/*else{//提示并返回到登录页面
				ServerHttpResponse originalResponse = exchange.getResponse();
				DataBufferFactory bufferFactory = originalResponse.bufferFactory();
				ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
					@Override
					public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
						if (body instanceof Flux) {
							Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
							return super.writeWith(fluxBody.map(dataBuffer -> {
								// probably should reuse buffers
								byte[] content = new byte[dataBuffer.readableByteCount()];
								dataBuffer.read(content);
								//释放掉内存
								DataBufferUtils.release(dataBuffer);
								String s = new String(content, Charset.forName("UTF-8"));
								s="yonghuxinnx";
								//TODO，s就是response的值，想修改、查看就随意而为了
								byte[] uppedContent = new String(content, Charset.forName("UTF-8")).getBytes();
								return bufferFactory.wrap(uppedContent);
							}));
						}
						// if body is not a flux. never got there.
						return super.writeWith(body);
					}
				};
				// replace response with decorator
				return chain.filter(exchange.mutate().response(decoratedResponse).build());
			}*/

		}





		// 1. 清洗请求头中from 参数
		ServerHttpRequest request = exchange.getRequest().mutate()
			.headers(httpHeaders -> {httpHeaders.remove(SecurityConstants.FROM);})
			.build();

		// 2. 重写StripPrefix
		addOriginalRequestUrl(exchange, request.getURI());
		String rawPath = request.getURI().getRawPath();
		String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
			.skip(1L).collect(Collectors.joining("/"));
		ServerHttpRequest newRequest = request.mutate()
			.path(newPath)
			.build();
		exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());

		return chain.filter(exchange.mutate()
			.request(newRequest.mutate()
				.build()).build());
	}

	@Override
	public int getOrder() {
		return -1000;
	}


	private boolean isExpire(String sessionId){
		SessionEntity sessionEntity=commonRedisUtil.getSessionEntity(sessionId);
		if(sessionEntity!=null){
			Long expireTime=commonRedisUtil.isExpire(sessionId);
			if(expireTime<=0){
				return false;
			}
		}else{
			return false;
		}
		return true;
	}

}
